<template>
  <el-dialog
    v-model="dialogVisible"
    title="分享文件"
    width="500px"
  >
    <div v-if="shareLink" class="share-result">
      <el-input
        v-model="shareLink"
        readonly
      >
        <template #append>
          <el-button @click="copyLink">复制链接</el-button>
        </template>
      </el-input>
      
      <div class="share-options">
        <el-form :model="shareForm" label-width="100px">
          <el-form-item label="有效期">
            <el-select v-model="shareForm.expireTime">
              <el-option label="1天" value="1" />
              <el-option label="7天" value="7" />
              <el-option label="30天" value="30" />
              <el-option label="永久" value="-1" />
            </el-select>
          </el-form-item>
          <el-form-item label="访问密码">
            <el-input v-model="shareForm.password" placeholder="为空则无需密码" />
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div v-else class="share-confirm">
      <p>确定要分享 "{{ file?.name }}" 吗？</p>
    </div>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">
          {{ shareLink ? '关闭' : '取消' }}
        </el-button>
        <el-button v-if="!shareLink" type="primary" @click="handleShare">
          确定分享
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { createShare } from '@/api/file'

const props = defineProps({
  modelValue: Boolean,
  file: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['update:modelValue', 'share-success'])

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const shareLink = ref('')
const shareForm = ref({
  expireTime: '7',
  password: ''
})

const handleShare = async () => {
  if (!props.file) return
  
  try {
    const res = await createShare({
      fileId: props.file.id,
      expireTime: parseInt(shareForm.value.expireTime),
      password: shareForm.value.password
    })
    shareLink.value = res.data.shareLink
    emit('share-success', shareLink.value)
  } catch (error) {
    ElMessage.error(error.message || '创建分享失败')
  }
}

const copyLink = async () => {
  try {
    await navigator.clipboard.writeText(shareLink.value)
    ElMessage.success('链接已复制到剪贴板')
  } catch (error) {
    ElMessage.error('复制失败，请手动复制')
  }
}
</script>

<style scoped>
.share-result {
  padding: 20px 0;
}

.share-options {
  margin-top: 20px;
}

.share-confirm {
  padding: 20px;
  text-align: center;
}
</style> 